import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {StorageService} from './storage.service';

@Injectable({
    providedIn: 'root',
})
export class HttpService {
    constructor(private httpClient: HttpClient, private storageService: StorageService) {
    }

    async get(url: string, param: {}) {
        return await this.request('GET', url, param, {});
    }

    async post(url: string, body: {}) {
        return await this.request('POST', url, {}, body);

    }

    async put(url: string, body: {}) {
        return await this.request('PUT', url, {}, body);
    }

    async delete(url: string, param: {}) {
        return await this.request('DELETE', url, param, {});
    }

    request(method: string = 'GET', url: string, params: any, body: any) {
        return new Promise<any>(async (resolve) => {
            let token = this.storageService.get('TOKEN');
            token = token ? token : '';
            this.httpClient.request(method, url, {params, body, headers: {token: token}}).subscribe((data) => {
                resolve(data);
            });
        });
    }
}
